from flask import Blueprint, request, jsonify, session, redirect, render_template
from pymysql import IntegrityError

from config import db
from models.models import Orders, ShopCar
from utils.utils import get_now_data_time

order_service = Blueprint('order_service', __name__)


@order_service.before_request
def session_checker():
    if 'user_id' not in session:
        return render_template('401.html')


@order_service.route('/user/order', methods=['POST'])
def get_order_info():
    try:
        user_id = session.get("user_id")

        order_data = request.get_json()
        for item in order_data:
            # 解析 JSON 数据
            good_id = item.get('good_id')
            name = item.get('name')
            price = item.get('price')
            number = item.get('number')
            _type = item.get('type')
            outline = item.get('outline')
            img_url = item.get('img_url')
            link_url = item.get('link_url')
            order = Orders(
                user_id=user_id,  # 这里到时候要改
                good_id=good_id,
                name=name,
                price=price,
                number=number,
                type=_type,
                outline=outline,
                img_url=img_url,
                link_url=link_url,
                create_time=get_now_data_time()
            )
            db.session.add(order)

            # 删除购物车中对应的商品项
            # 这个地方固定能运行，但是order以后上去就没法实现，需要调试
            cart_item = ShopCar.query.filter_by(user_id=user_id, good_id=good_id).first()
            if cart_item:
                db.session.delete(cart_item)

        db.session.commit()  # 提交事务

        return jsonify({"message": "Order submitted successfully"}), 200

    except IntegrityError as e:
        db.session.rollback()
        return jsonify({"error": "Error submitting order"}), 500


@order_service.route('/user/order')
def get_order_info_get():
    user_id = session.get("user_id")
    types = Orders.query.filter_by(user_id=user_id)

    data = []
    for _type in types:
        value = {
            "order_id": _type.id,
            "user_id": _type.user_id,
            "good_id": _type.good_id,
            "name": _type.name,
            "price": _type.price,
            "number": _type.number,
            "type": _type.type,
            "outline": _type.outline,
            "img_url": _type.img_url,
            "link_url": _type.link_url,
            "create_time": _type.create_time
        }
        data.append(value)
    return jsonify({'code': 0, 'msg': '', 'data': data})


@order_service.route('/add/order/good', methods=['POST'])
def add_order_good():
    user_id = session.get("user_id")
    if request.method == 'POST':
        good_id = request.form.get('good_id')
        name = request.form.get('name')
        price = request.form.get('price')
        number = request.form.get('number')
        _type = request.form.get('type')
        outline = request.form.get('outline')
        img_url = request.form.get('img_url')
        link_url = request.form.get('link_url')
        order = Orders(
            user_id=user_id,
            good_id=good_id,
            name=name,
            price=price,
            number=number,
            type=_type,
            outline=outline,
            img_url=img_url,
            link_url=link_url,
            create_time=get_now_data_time()
        )
        db.session.add(order)
        db.session.commit()
        return redirect('/user/manage')
    return "请求失败"
